﻿using System.Text;
using Deer.Extension;
using Letter.IO.Binary;
using Letter.IO.Pipes;

namespace Telex;

static class PipelineWriterExtension
{
    private const int HEAD_SIZE = 4;
    private const int GUID_SIZE = 16;
    
    public static void DeliverSecretkeyReqPack(this APipelineWriter outer, string secretkey)
    {
        var writer = outer.ToBytesWriter();
        var hBuf = writer.Mark(HEAD_SIZE);
        var secretkeyBytes = Encoding.UTF8.GetBytes(secretkey);
        writer.WriteUInt8((byte)Command.SECRET_KEY_REQ);
        writer.WriteBytes(secretkeyBytes);
        hBuf.FWriteInt32BE(secretkeyBytes.Length + 1);

        outer.FlushAsync().Sync();
    }

    public static void DeliverSecretkeyResPack(this APipelineWriter outer, byte status)
    {
        var writer = outer.ToBytesWriter();
        var hBuf = writer.Mark(HEAD_SIZE);
        
        writer.WriteUInt8((byte)Command.SECRET_KEY_RES);
        writer.WriteUInt8(status);
        hBuf.FWriteInt32BE(2);
        
        outer.FlushAsync().Sync();
    }

    public static void DeliverHostOptions(this APipelineWriter outer, RpcHost host)
    {
        var writer = outer.ToBytesWriter();
        var hBuf = writer.Mark(HEAD_SIZE);
        
        writer.WriteUInt8((byte)Command.SYNC_HOST_OPTIONS);
        
        var cBuf = Encoding.UTF8.GetBytes(host.clusterId);
        writer.WriteInt32BE(cBuf.Length);
        writer.WriteBytes(cBuf);
        
        var sBuf = Encoding.UTF8.GetBytes(host.serviceId);
        writer.WriteInt32BE(sBuf.Length);
        writer.WriteBytes(sBuf);

        hBuf.FWriteInt32BE(4 + cBuf.Length + 4 + sBuf.Length + 1);
        
        outer.FlushAsync().Sync();
    }
}